/***
 * handles user
 *
 *
 **/
session_start();

require 'db.php';

if( !is_string($_REQUEST['type']) ) {
  // error BREAK
}

switch( $_REQUEST['type'] ) {
  case 'REGISTER':
    handleRegister(); break;
  case 'LOGIN':
    handleLogin(); break;
  case 'LOGOUT':
    handleLogout(); break;
  default:
    break;
}

function handleRegister() {
  if( is_string($_POST['user']) && is_string($_POST['pass']) 
      && is_string( $_POST['email'] ) ) {
    // XXX validate variables;
    $user = $_POST['user'];
    $pass = sha2($_POST['pass']);
    $email = $_POST['email'];
    try {
      $db = new PDO($db_name, $db_user, $db_pass, $db_options);
      $db->query("INSERT INTO user (name, pass, email) 
                    VALUES ($user, $pass, $email) ");
      } catch ( PDOException $e ) {
        print "ERROR: " . $e->getMessage() . "<br />";
        die();
      }
  } 
}
function handleLogin() {
  if( is_string($_POST['user']) && is_string($_POST['pass']) ) {
    //XXX validate user and pass
    $user = $_POST['user'];
    $pass = sha2($_POST['pass']);
    try {
      $db = new PDO($db_name, $db_user, $db_pass, $db_options);
      $db->query("SELECT uid, name FROM user 
                    WHERE name = $user
                      AND pass = $pass");
      // TODO does this show success
      if( $db ) {
        $_SESSION['uid'] = $db['uid'];
        $_SESSION['uname'] = $db['name'];
      }
      $db->closeCursor();
    } catch ( PDOException $e ) {
      print "ERROR: " . $e->getMessage() . "<br />";
      die();
    }   
  }
}
function handleLogout() {
  session_destroy();
}
